package com.hedl.practice.diyJava.reflex;

public class JavaAndReflex {
    public static void main(String[] args) throws ClassNotFoundException {

       /* printClassInfo("".getClass());
        printClassInfo(Runnable.class);
        printClassInfo(java.time.Month.class);
        printClassInfo(String[].class);
        printClassInfo(int.class);*/

        //方法一
        Class cls = String.class;
        System.out.println("方法一:"+cls);

        //方法二
        String s = "Hello";
        Class cls1 = s.getClass();
        System.out.println("方法二:"+cls1);

        //方法三
        Class cls2 = Class.forName("java.lang.String");
        System.out.println("方法三:"+cls2);

        //比较instanceof和==号的区别
        /**
         * 用instanceof不但匹配指定类型，还匹配指定类型的子类；
         * 而用==判断class实例可以精确地判断数据类型，但不能作子类型比较；
         */
        Integer n = new Integer(123);

        boolean b1 = n instanceof Integer;
        boolean b2 = n instanceof Number;
        System.out.println("instanceof比较："+b1);
        System.out.println("instanceof比较："+b2);

        boolean b3 = n.getClass()==Integer.class;
        //boolean b4 = n.getClass()==Number.class;        //不可比较类型
        System.out.println("==比较："+b3);
        //System.out.println("==比较："+b4);


        Class c1 = String.class;        //获取String的Class实例:
        System.out.println(c1);
        try {
            /**
             * 通过Class.newInstance()可以创建类实例，它的局限是：
             * 只能调用public的无参数构造方法。带参数的构造方法，或者非public的构造方法都无法通过Class.newInstance()被调用。
             */
            String s1 = (String) c1.newInstance();      //创建一个String实例:
            System.out.println(s1);
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }


    }

    static void printClassInfo(Class cls){
        System.out.println("Class name:"+cls.getName());
        System.out.println("Simple name:"+cls.getSimpleName());
        if (cls.getPackage() != null){
            System.out.println("Package name:"+cls.getPackage().getName());
        }
        System.out.println("is interface:"+cls.isInterface());
        System.out.println("is enum:"+cls.isEnum());
        System.out.println("is Array:"+cls.isArray());
        System.out.println("is primitive:"+cls.isPrimitive());
    }
}
